Practice Problems of EventListener and Browser Events in JS
Practice problems of EventListener and Browser Events in JavaScript. These problems are designed to help you understand the concept of EventListener and Browser Events in JavaScript. You can practice these problems to improve your skills in JavaScript.
1. Toggle Button Text
Task: Create a button that toggles its text between "Start" and "Stop" every time it's clicked.
Code:-
<button id="toggleBtn">Start</button>
<script>
const toggleBtn = document.getElementById('toggleBtn');
toggleBtn.addEventListener('click', () => {
toggleBtn.textContent = toggleBtn.textContent === 'Start' ? 'Stop' : 'Start';
});
</script>
2. Live Character Counter
Task: Build a text area with a live character counter below it (e.g., "Characters: 42").
Code:-
<textarea id="textInput" rows="4" cols="30"></textarea>
<p id="charCount">Characters: 0</p>
<script>
const textInput = document.getElementById('textInput');
const charCount = document.getElementById('charCount');
textInput.addEventListener('input', () => {
charCount.textContent = `Characters: ${textInput.value.length}`;
});
</script>
3. Add & Remove Event Listener
Task: Add a click event to a button that logs a message. Create another button that removes this listener when clicked.
Code:-
<button id="logBtn">Click Me</button>
<button id="removeListenerBtn">Remove Listener</button>
<script>
const logBtn = document.getElementById('logBtn');
const removeBtn = document.getElementById('removeListenerBtn');
function handleClick() {
console.log('Button was clicked!');
}
logBtn.addEventListener('click', handleClick);
removeBtn.addEventListener('click', () => {
logBtn.removeEventListener('click', handleClick);
console.log('Listener removed.');
});
</script>
4. Event Delegation: Dynamic List Items
Task: Make a <ul> that allows clicking on any <li> to highlight it. New <li> elements added via JavaScript should also work without attaching new event listeners.
Code:-
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button id="addItem">Add Item</button>
<script>
const list = document.getElementById('myList');
const addItem = document.getElementById('addItem');
list.addEventListener('click', (e) => {
if (e.target.tagName === 'LI') {
e.target.style.backgroundColor = '#d0f0c0';
}
});
addItem.addEventListener('click', () => {
const newItem = document.createElement('li');
newItem.textContent = `Item ${list.children.length + 1}`;
list.appendChild(newItem);
});
</script>
5. Keyboard Shortcuts
Task: Listen for keyboard events and display a message like "You pressed: A" in a <div>. Add logic to trigger a specific function if Ctrl + S is pressed.
Code:-
<p id="keyOutput">Press a key...</p>
<script>
const keyOutput = document.getElementById('keyOutput');
document.addEventListener('keydown', (e) => {
keyOutput.textContent = `You pressed: ${e.key}`;
if (e.ctrlKey && e.key.toLowerCase() === 's') {
e.preventDefault();
alert('Ctrl + S was pressed! Saving...');
}
});
</script>